package com.longchat.service.impl.upload;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.longchat.domain.system.User;
import com.longchat.domain.upload.Express;
import com.longchat.dto.comm.ResultEnum;
import com.longchat.dto.comm.ResultInfo;
import com.longchat.repository.upload.ExpressJpaRepository;
import com.longchat.service.inter.upload.IExpressService;
import com.longchat.utils.Constant;
import com.longchat.utils.DateUtil;
import com.longchat.utils.Utils;
import com.longchat.utils.excel.util.DownExcel;

@Service
public class ExpressService implements IExpressService {
	
	@Value("${imageURL}")
    private String imageURL;
	@Autowired
	private ExpressJpaRepository expressJpaRepository;

	@Override
	public ResultInfo importExpressInfoFile(MultipartFile file, User us) {
		ResultInfo rs = new ResultInfo(ResultEnum.SUCCESS);
        String fileExt= file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1).toLowerCase();//扩展名
        Date dt = new Date();
        String fileName = DateUtil.getInstance().getDateStr(dt,DateUtil.yyyyMMddHHmmss)+"."+fileExt;
        String filePatch = Constant.EXPRESS_IMP + File.separator + DateUtil.getInstance().getYear(dt) + File.separator + DateUtil.getInstance().getMonth(dt);
        File upFile = new File(imageURL + File.separator +filePatch + File.separator + fileName);
        if(!upFile.getParentFile().exists()){
            upFile.getParentFile().mkdirs();
        }
//        User us = SessionData.getInstance().getUser(request);
        //上传文件
//        String rtStr = FileUtil.saveImageFile(file, imageURL, filePatch, fileName);
        //调用Excel解析
        Map<String,Object> map = GetObjInfOfExcel(upFile,fileExt);
        if(Utils.isEmptyString(map.get("errorBack").toString())){
            List<Express> impList=(List<Express>)map.get("objTList");
            if(null != impList && impList.size() >0){
                //保存导入的数据
            	try {
					rs = saveMapImprt(impList, us);
					if(rs.getCode() != 200){
						upFile.delete();
						return new ResultInfo(500, rs.getMessage());
					}
				} catch (Exception e) {
					
					e.printStackTrace();
				}
            }else{
                upFile.delete();
                return new ResultInfo(500, "请填写导入数据！");
            }
        }else{
            upFile.delete();
            return new ResultInfo(500, (String)map.get("errorBack"));
        }
        return rs;
	}
	
	/**
     * <分析Excel，组装显示在页面中>
     *
     * @param file               文件信息
     * @param uploadFileFileName 文件后缀名
     * @param tip                生成用户,职责,OA用户信息
     */
    public Map<String,Object> GetObjInfOfExcel(File file,String uploadFileFileName){
        return DownExcel.getInstall().getExpressInfOfExcel(file,uploadFileFileName);
    }
    
    /**
     * 号码导入数据校验入库
     * @param impList
     * @return
     * @throws Exception
     */
    @Transactional
    public ResultInfo saveMapImprt(List<Express> impList, User us) throws Exception{
    	ResultInfo rs = new ResultInfo(ResultEnum.SUCCESS);

        Date date = new Date();
        
        //分批基础数据校验
        Integer dataCount = impList.size();
        int page = 0;//页数
        int pageCount = 10000;
        List<Express> list;
        if(dataCount > pageCount){
            if(dataCount%pageCount !=0){
                page = dataCount/pageCount +1;
            }else{
                page = dataCount/pageCount;
            }
            int start=0,end=0;
            for (int i = 1; i <= page; i++) {
            	list = new ArrayList<Express>();
                if (i * pageCount > dataCount) {
                    end = dataCount;
                } else {
                    end = i * pageCount;
                }
                if (i == 1) {
                    start = i - 1;
                } else {
                    start = (i - 1) * pageCount;
                }
                for (int j = start; j < end; j++) {
                	list.add(impList.get(j));
				}
                expressJpaRepository.save(list);
            }
        }else {
        	expressJpaRepository.save(impList);
        }
        
        return rs;
    }

}
